import Reflux from 'reflux';
import {Control} from 'react-keeper';
import Actions from './Actions';
import DB from '../../../../app/db';
import update from 'react-addons-update';
import StorageUtils from "../../../../app/storage";
import {Toast, Modal} from 'antd-mobile';
import {generateUUID, dateToFullString} from "../Const";

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    userInfo: {},
    subjectId: '',
    isNew: false,
    subject: {},
    questions: [{
      subjectId: null,
      title: '',
      description: '',
      type: 'Single',
      options: []
    }],
    pagination: {
      total: 1,
      current: 1,
      questionId: null,
      question: {}
    },
    isLoading: true,
  },

  customInit(subjectId) {
    this.data.isLoading = true;
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getUser()}});
    this.data.subjectId = subjectId;
    this.updateComponent();
    this.getSubjectById();
    this.getQuestions();
  },

  initQuestions() {
    let questionId = generateUUID();
    this.data.questions = [{
      id: questionId,
      subjectId: this.data.subjectId,
      title: '',
      description: '',
      type: 'Single',
      disabledSwipeAction: true,
      options: [
        {
          id: generateUUID(),
          questionId: questionId,
          optionDesc: '',
          disabledSwipeAction: true,
        },
        {
          id: generateUUID(),
          questionId: questionId,
          optionDesc: '',
          disabledSwipeAction: true,
        }
      ]
    }];
    this.data.pagination = update(this.data.pagination, {
      total: {$set: 1},
      current: {$set: 1},
      questionId: {$set: questionId},
      question: {$set: this.data.questions[0]}
    });
    this.updateComponent();
  },

  getSubjectById() {
    let t = this;
    DB.vote.getSubjectById({id: t.data.subjectId}).then(
      function (content) {
        if (content) {
          t.data.subject = content;
          t.data.isLoading = false;
          t.updateComponent();
        } else {
          t.data.subject = {
            id: t.data.subjectId,
            title: '',
            description: '',
            status: '草稿',
            endTime: dateToFullString(new Date(Date.now()), '/'),
            voteCount: 0,
            creatorId: t.data.userInfo.proprietorId
          };
          t.data.isLoading = false;
          t.updateComponent();
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getQuestions() {
    let t = this;
    DB.vote.allQuestionBySubjectId({subjectId: t.data.subjectId}).then(
      function (content) {
        if (content && content.length > 0) {
          t.data.questions = content;
          t.data.pagination = update(t.data.pagination, {
            total: {$set: content.length},
            current: {$set: 1},
            questionId: {$set: content[0].id},
            question: {$set: content[0]}
          });
          t.getOptionsByQuestionId(content[0].id);
        } else {
          t.initQuestions();
        }
      },
      function (error) {
        console.log(error);
        t.initQuestions();
      }
    );
  },

  addQuestion() {
    const uuid = generateUUID();
    let questions = this.data.questions;
    questions.push({
      id: uuid,
      subjectId: this.data.subjectId,
      title: '',
      description: '',
      type: 'Single',
      index: 1,
      isNew: true,
      disabledSwipeAction: true,
      options: [
        {
          id: generateUUID(),
          questionId: uuid,
          optionDesc: '',
          isNew: true,
          disabledSwipeAction: true
        },
        {
          id: generateUUID(),
          questionId: uuid,
          optionDesc: '',
          isNew: true,
          disabledSwipeAction: true
        }
      ]
    });
    this.data.questions = questions;
    this.data.pagination = update(this.data.pagination, {
      total: {$set: questions.length},
      current: {$set: questions.length},
      questionId: {$set: uuid},
      question: {$set: questions[questions.length-1]}
    });
    this.updateComponent();
  },

  delQuestion() {
    let t = this;
    Modal.alert('确认', '删除后无法恢复，是否删除？', [
      {
        text: '删除',
        onPress: () => {
          let current = t.data.pagination.current;
          let delQuestion;
          let questions = [];
          t.data.questions.map( (q, i) => {
            if (i !== current-1) {
              questions.push(q);
            } else {
              delQuestion = q;
            }
          });
          if (delQuestion.isNew) {
            if (questions.length === 0) {
              t.initQuestions();
            } else {
              current = questions.length > current ? current : questions.length;
              t.data.questions = questions;
              t.data.pagination = update(t.data.pagination, {
                total: {$set: questions.length},
                current: {$set: current},
                questionId: {$set: questions[current-1].id},
                question: {$set: questions[current-1]}
              });
              t.updateComponent();
              t.getOptionsByQuestionId(t.data.questions[t.data.pagination.current-1].id);
            }
          } else {
            DB.vote.delQuestionById({id: delQuestion.id}).then(
              function (content) {
                if (content) {
                  t.getQuestions();
                  Toast.success('删除成功');
                } else {
                  Toast.fail('删除失败');
                }
              },
              function (error) {
                console.log(error);
              }
            );
          }
        },
        style: 'default'
      },
      {
        text: '取消',
        onPress: () => {},
        style: 'default'
      }
    ]);
  },

  getOptionsByQuestionId(questionId) {
    let t = this;
    let question = t.data.questions.find(q=>{
      return q.id === questionId;
    });

    if (question.hasOwnProperty('options')) {
      t.data.pagination.question = question;
      t.updateComponent();
    } else {
      DB.vote.allOptionByQuestionId({questionId: questionId}).then(
        function (content) {
          if (content && content.length > 0) {
            let disabledSwipeAction = content.length <= 2;
            let opts = update(content, {$apply: opts => {
              return opts.map(opt => {
                return update(opt, {
                  disabledSwipeAction: {$set: disabledSwipeAction}
                });
              });
            }});
            let questionChanged;
            t.data.questions = update(t.data.questions, {$apply: (questions) => {
              return questions.map(q => {
                if (q.id === questionId) {
                  questionChanged = update(q, {
                    options: {$set: opts},
                    disabledSwipeAction: {$set: disabledSwipeAction}
                  });
                  return questionChanged;
                } else {
                  return q;
                }
              });
            }});
            t.data.pagination.question = questionChanged;
            t.updateComponent();
          }
        },
        function (error) {
          console.log(error);
        }
      );
    }
  },

  addOption() {
    let t = this;
    let question = t.data.questions[t.data.pagination.current-1];
    t.data.questions = update(t.data.questions, {$apply: (questions) => {
      return questions.map(q=>{
        if (q.id === t.data.pagination.questionId) {
          let options = q.options;
          /*if (q.hasOwnProperty('options')) {
            options = q.options;
          }*/
          let disabledSwipeAction = (options.length + 1) <= 2;
          options.push({
            id: generateUUID(),
            questionId: q.id,
            optionDesc: '',
            isNew: true,
            disabledSwipeAction: true
          });
          options = update(options, {$apply: opts => {
            return opts.map(opt => {
              return update(opt, {
                disabledSwipeAction: {$set: disabledSwipeAction}
              });
            })
          }});
          question = update(q, {
            options: {$set: options},
            disabledSwipeAction: {$set: disabledSwipeAction}
          });
          return question;
        } else {
          return q;
        }
      })
    }});
    t.data.pagination.question = question;
    t.updateComponent();
  },

  delOption(delOption) {
    let t = this;
    let currentQuestion;
    DB.vote.delOptionById({id: delOption.id}).then(
      function (content) {
        if (content) {
          t.data.questions = update(t.data.questions, {$apply: questions => {
            return questions.map(q=>{
              if (q.id === delOption.questionId) {
                let disabledSwipeAction = (q.options.length - 1) <= 2;
                currentQuestion = update(q, {
                  options: {$apply: options => {
                    return options.filter(o=>{
                      return o.id !== delOption.id;
                    })
                  }}
                });
                currentQuestion = update(currentQuestion, {
                  options: {$apply: options => {
                    return options.map(opt => {
                      return update(opt, {
                        disabledSwipeAction: {$set: disabledSwipeAction}
                      })
                    })
                  }}
                });
                currentQuestion.disabledSwipeAction = disabledSwipeAction;
                return currentQuestion;
              } else {
                return q;
              }
            })
          }});
          t.data.pagination = update(t.data.pagination, {
            question: {$set: currentQuestion}
          });
          t.updateComponent();
        }
      }
    );
  },

  onPaginationChange(index) {
    let t = this;
    let curQuestion = t.data.questions[index-1];
    if (curQuestion.hasOwnProperty('options')) {
      t.data.pagination = update(t.data.pagination, {
        current: {$set: index},
        questionId: {$set: curQuestion.id},
        question: {$set: curQuestion}
      });
      t.updateComponent();
    } else {
      DB.vote.allOptionByQuestionId({questionId: curQuestion.id}).then(
        function (content) {
          if (content && content.length > 0) {
            let disabledSwipeAction = content.length <= 2;
            t.data.questions = update(t.data.questions, {$apply: (questions) => {
              return questions.map(q => {
                if (q.id === curQuestion.id) {
                  return update(q, {
                    options: {$set: update(content, {$apply: opts => {
                      return opts.map(opt=>{
                        return update(opt, {
                          disabledSwipeAction: {$set: disabledSwipeAction}
                        });
                      });
                    }})},
                    disabledSwipeAction: {$set: disabledSwipeAction}
                  });
                } else {
                  return q;
                }
              });
            }});
            t.data.pagination = update(t.data.pagination, {
              current: {$set: index},
              questionId: {$set: curQuestion.id},
              question: {$set: t.data.questions[index-1]}
            });
            t.updateComponent();
          }
        },
        function (error) {
          console.log(error);
        }
      );
    }
  },

  onSubjectTitleInput(val) {
    let t = this;
    t.data.subject = update(t.data.subject, {
      title: {$set: val}
    });
    t.updateComponent();
  },

  onSubjectDescriptionInput(val) {
    let t = this;
    t.data.subject = update(t.data.subject, {
      description: {$set: val}
    });
    t.updateComponent();
  },

  onSubjectEndTimeInput(val) {
    let t = this;
    t.data.subject = update(t.data.subject, {
      endTime: {$set: dateToFullString(val, '/')}
    });
    t.updateComponent();
  },

  onQuestionTitleInput(val, q) {
    let t = this;
    let questionChanged;
    t.data.questions = update(t.data.questions, {$apply: (questions) => {
      return questions.map(question => {
        if (question.id === q.id) {
          questionChanged = update(question, {
            title: {$set: val}
          });
          return questionChanged;
        } else {
          return question;
        }
      })
    }});
    t.data.pagination.question = questionChanged;
    t.updateComponent();
  },

  onQuestionDescriptionInput(val, q) {
    let t = this;
    let questionChanged;
    t.data.questions = update(t.data.questions, {$apply: (questions) => {
      return questions.map(question => {
        if (question.id === q.id) {
          questionChanged = update(question, {
            description: {$set: val}
          });
          return questionChanged;
        } else {
          return question;
        }
      })
    }});
    t.data.pagination.question = questionChanged;
    t.updateComponent();
  },

  onQuestionTypeChange(value, question) {
    let questionChanged;
    this.data.questions = update(this.data.questions, {$apply: (questions) => {
      return questions.map(q => {
        if (q.id === question.id) {
          questionChanged = update(q, {
            type: {$set: !value ? 'Single' : 'Multi'}
          });
          return questionChanged;
        } else {
          return q;
        }
      })
    }});
    this.data.pagination.question = questionChanged;
    this.updateComponent();
  },

  onOptionDescriptionInput(val, o) {
    let t = this;
    let questionChanged;
    t.data.questions = update(t.data.questions, {$apply: (questions) => {
      return questions.map(q => {
        if (q.id === o.questionId) {
          questionChanged = update(q, {
            options: {$apply: (options) => {
              return options.map(option => {
                if (option.id === o.id) {
                  return update(option, {
                    optionDesc: {$set: val}
                  });
                } else {
                  return option;
                }
              });
            }}
          });
          return questionChanged;
        } else {
          return q;
        }
      })
    }});
    this.data.pagination.question = questionChanged;
    t.updateComponent();
  },

  onSave() {
    this.doSave('草稿');
  },

  onPublish() {
    this.doSave('进行中');
  },

  doSave(status) {
    let t = this;
    let s = t.data.subject;
    let qs = t.data.questions;
    let paramQ = [];
    if (qs && qs.length > 0) {
      qs.map((q, qi)=>{
        let paramO = [];
        if (q.options && q.options.length > 0) {
          q.options.map((o, oi)=>{
            paramO.push({
              id: o.id,
              orderNum: oi+1,
              questionId: o.questionId,
              optionDesc: o.optionDesc,
              delFlag: 0
            });
          });
        }
        paramQ.push({
          id: q.id,
          subjectId: q.subjectId,
          title: q.title,
          description: q.description,
          type: q.type,
          orderNum: qi+1,
          options: paramO
        });
      })
    }
    let params = {
      id: s.id,
      title: s.title,
      description: s.description,
      status: status,
      endTime: s.endTime,
      voteCount: s.voteCount,
      delFlag: s.delFlag,
      creatorId: s.creatorId,
      questions: paramQ,
      areas: [{
        area: '',
        subjectId: s.id
      }]
    };
    DB.vote.saveSubject({param: JSON.stringify(params)}).then(
      function (content) {
        if (content.success) {
          if (status === '草稿') {
            Toast.success('保存成功');
            t.customInit(content.subjectId);
            Control.replace('/home/vote/edit/'+content.subjectId);
          } else {
            Toast.success('发布成功');
            Control.replace('/home/vote/');
          }
        } else {
          Toast.fail('保存失败');
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  subjectInputCheck() {
    let t = this;
    console.log('subjectInputCheck');
    let subject = t.data.subject;
    console.log(subject);
    if (!(subject.title && subject.title.length > 0)) {
      Toast.fail('请填写问卷名称!');
      return false;
    }
  },

  questionInputCheck() {
    console.log('questionInputCheck');
    let t = this;
    t.data.questions.map(q => {

    });
    let question = t.data.questions[t.data.pagination.current-1];
    console.log(question.title);
    if (!(question.title && question.title.length > 0)) {
      Toast.fail('请填写问题!');
      return false;
    }

    question.options.map(o => {
      if (!(o.optionDesc && o.optionDesc.length > 0)) {
        Toast.fail('请填写问题选项!');
        return false;
      }
    });
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
